const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}

const isURL = (s) => {
  return /^http[s]?:\/\/.*/.test(s)
}

const measureTexts = (ctx, contentTitle, winWidth) => {
  var chr = contentTitle.split(""); //这个方法是将一个字符串分割成字符串数组
  var temp = "";
  var row = [];
  for (var a = 0; a < chr.length; a++) {
    if (ctx.measureText(temp).width < winWidth / 2 - 10) {
      temp += chr[a];
    } else {
      a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
      row.push(temp);
      temp = "";
    }
  }
  row.push(temp);
  //如果数组长度大于2 则截取前两个
  if (row.length > 2) {
    var rowCut = row.slice(0, 2);
    var rowPart = rowCut[1];
    var test = "";
    var empty = [];
    for (var a = 0; a < rowPart.length; a++) {
      if (ctx.measureText(test).width < winWidth / 2 - 10) {
        test += rowPart[a];
      } else {
        break;
      }
    }
    empty.push(test);
    var group = empty[0] + "..." //这里只显示两行，超出的用...表示
    rowCut.splice(1, 1, group);
    row = rowCut;
  }
  return row
}

// 获取对应格式日期
const nowTime = (pattern)=>{ // 获取当前时间
  var now = new Date()
  var year = now.getFullYear() // 年
  var month = now.getMonth() + 1 // 月
  var lastMonth = now.getMonth() // 上月
  var day = now.getDate() // 日
  var hh = now.getHours() // 时
  var mm = now.getMinutes() // 分
  var ss = now.getSeconds() // 秒
  if (month < 10) {
    month = '0' + month
  }
  if (lastMonth < 10) {
    lastMonth = '0' + lastMonth
  }
  if (day < 10) {
    day = '0' + day
  }
  if (hh < 10) {
    hh = '0' + hh
  }
  if (mm < 10) {
    mm = '0' + mm
  }
  if (ss < 10) {
    ss = '0' + ss
  }
  if (pattern === 'time') {
    return hh + ':' + mm + ':' + ss // 获取当前时间
  } else if (pattern === 'year') {
    return year // 获取当前年份
  } else if (pattern === 'month') {
    return month // 获取当前月份
  } else if (pattern === 'yearMonth') {
    return year + '-' + month // 获取当前月份
  } else if (pattern === 'YM') {
    return year + '-' + lastMonth // 获取当年上月
  } else if (pattern === 'date') {
    return year + '-' + month + '-' + day // 获取当前日期
  } else if (pattern === 'yesdate') {
    return year + '-' + month + '-' + (day-1) // 获取昨天日期
  } else if (pattern === 'allTime') {
    return year + '-' + month + '-' + day + ' ' + hh + ':' + mm + ':' + ss // 获取日期与时间
  }
}

module.exports = {
  formatTime: formatTime,
  isURL: isURL,
  measureTexts: measureTexts,
  formatDate:formatDate,
  nowTime:nowTime
}
